package com.ling.pl.core.context;

import com.ling.pl.core.commons.utils.AssertHelper;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 默认的ContextSecurity实现,如果需要覆盖请在自己的实现上添加@Primary
 */
@Component
public class DefaultContextSecurity extends BaseContextSecurity {
    /**
     * token部分 模拟登录
     */
    @Override
    public void login(Object userInfo) {
        HttpServletRequest request = ContextHolder.getRequest();
        HttpServletResponse response = ContextHolder.getResponse();
        //生产token
        Token token = new Token();
        token.setSid(UUID.randomUUID().toString());//设置用于缓存的全局唯一id
        token.setUserCode("test");
        token.setUserName("test");
        token.setCreationTime(System.currentTimeMillis());
        login(token, request, response);
    }

    //todo 需要结合其他机制来判断用户是否在当前session登录,比如spring security或ibz的方法
    public boolean isLogin(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        Object token = session.getAttribute(cookieTokenKey);
        return AssertHelper.notEmpty(token);
    }

    ///todo 这里需要设置token过期时间,需要写到文档说明中
    protected int getTokenValiditySeconds() {
        return TWO_WEEKS_S;
    }

}
